package com.example.androidxdemo.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.widget.addTextChangedListener
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.Observer
import androidx.navigation.fragment.findNavController
import com.blankj.utilcode.util.ToastUtils
import com.example.androidxdemo.databinding.FragmentLoginBinding
import com.example.androidxdemo.viewModel.LoginViewModel
import kotlinx.android.synthetic.main.fragment_login.*

/**
 * @author : yaobing
 * @date   : 2020/7/20 9:53
 * @desc   :
 */

class LoginFragment : BaseFragment() {
    var binding: FragmentLoginBinding? = null
    private val loginViewModel by activityViewModels<LoginViewModel>()

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentLoginBinding.inflate(inflater, container, false)
        return binding?.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        username.addTextChangedListener {
            login.isEnabled = "" != it.toString()
        }

        login.setOnClickListener {
            loginViewModel.login(username.text.toString(), password.text.toString())
        }

        logout.setOnClickListener {
            loginViewModel.logout(true)
        }

        loginViewModel.authenticationState.observe(
            viewLifecycleOwner,
            Observer { authenticationState ->
                @Suppress("NON_EXHAUSTIVE_WHEN")
                when (authenticationState){
                    LoginViewModel.AuthenticationState.AUTHENTICATED -> {
                        ToastUtils.showLong("登录成功")
                        findNavController().popBackStack()
                    }
                    LoginViewModel.AuthenticationState.INVALID_AUTHENTICATION -> {
                        ToastUtils.showLong("登录失败")
                    }
                    LoginViewModel.AuthenticationState.CANCEL_AUTHENTICATION -> {
                        findNavController().popBackStack()
                    }
                }

            })
    }

    override fun onDestroyView() {
        super.onDestroyView()
        binding = null
        if (loginViewModel.authenticationState.value != LoginViewModel.AuthenticationState.AUTHENTICATED) {
            loginViewModel.setUnauthenticated()
        }
    }
}